import GoEasy from 'goeasy-lite'
import useAppStore from "@/pinia"

const formatMessage = (action = 'sendIndexChat', message = "") => {
    const app = useAppStore()
    let result = {}
    if (action) {
        if (action == 'sendIndexChat') {
            result = {
                action,
                message,
                user: {
                    userId: app.userInfo.userId,
                    name: app.userInfo.name,
                }
            }
        }
        result = JSON.stringify(result)
        return result
    }
    else return false
}

class GoEasyBase {
    goEasy: any
    hasJoinChannel: String[] = []
    watchList: any[] = []
    constructor() {
        this.goEasy = GoEasy.getInstance({
            host: "hangzhou.goeasy.io",
            appkey: "BC-3804213eb22d49b3956b7b9c859f3a02",
            modules: ['pubsub']
        })
        this.init()
    }

    init() {
        this.goEasy.connect({
            onSuccess: () => {
                console.log("goEasy 连接成功")
            },
            onFailed: (err: any) => {
                const hasConnect = err.code === 408 && err.content.indexOf("It is already connected") !== -1
                if (hasConnect) {
                    console.log("goEasy 已经连接")
                } else {
                    console.log("goEasy 连接失败", err)
                }
            },
            onProgress: (attempts: number) => {
                console.log("goEasy 连接中", attempts)
            },
        })
    }

    // 断开连接
    disconnectGoEasy() {
        this.goEasy.disconnect({
            onSuccess: function() {
                console.log("GoEasy disconnect已断开连接")
            },
            onFailed: function(error: any) {
                console.log("GoEasy disconnect断开连接失败", error)
            },
        })
        // this.unsubscribeGoEasy().finally(() => {
        // 先取消订阅再断开连接
        // })
    }

    // 订阅频道
    subscribeGoEasy(channel = "") {
        if (this.hasJoinChannel.length) {
            if (this.hasJoinChannel.find(i => i == channel)) {
                console.log("subscribeGoEasy 已经订阅该频道")
                return
            }
        }
        this.goEasy.pubsub.subscribe({
            channel,
            onMessage: (message: any) => {
                console.log(channel + "频道收到消息：", message)
                this.watchList.forEach((item) => {
                    item.cb(message)
                })
            },
            onSuccess: () => {
                console.log("Channel订阅成功 channel：" + channel)
                this.hasJoinChannel.push(channel)
            },
            onFailed: (error: any) => {
                console.log("Channel订阅失败 channel：" + channel, error)
            },
        })
    }

    // 取消订阅
    unsubscribeGoEasy(channel: string = "") {
        return new Promise((resolve, reject) => {
            if (channel) {
                this.goEasy.pubsub.unsubscribe({
                    channel,
                    onSuccess: () => {
                        console.log("取消订阅成功 channel：", channel)
                        resolve({})
                    },
                    onFailed: (error: any) => {
                        console.log("取消订阅失败 channel：" + channel, error)
                        reject(error)
                    },
                })
            } else {
                console.log("取消订阅失败 参数错误")
                reject()
            }
        })
    }

    // 发送消息
    sendMessage(channel: string = '', action = 'sendIndexChat', message: any = "") {
        if (channel) {
            message = formatMessage(action, message)
            if (message) this.goEasy.pubsub.publish({
                channel,
                message,
                onSuccess: () => {
                    console.log("sendMessage 消息发布成功")
                },
                onFailed: (error: any) => {
                    console.log("消息发送失败", error)
                },
            })
            else console.log("sendMessage 发送信息 参数错误 action, message", action, message)
        } else {
            console.log("sendMessage 消息发送失败 参数错误 channel为空")
        }
    }

    // 获取历史消息
    getHistoryMessage(channel: string) {
        return new Promise((resolve, reject) => {
            this.goEasy.pubsub.history({
                channel,
                limit: 30, // 返回的消息条数 最多30条
                onSuccess: (response: any) => {
                    resolve(response)
                },
                onFailed: (error: any) => {
                    reject(error)
                },
            })
        })
    }

    onMessage(watchPage = '', cb: any = () => { }) {
        let hasIndex = this.watchList.findIndex((item) => item.watchPage == watchPage)
        if (hasIndex > -1) this.watchList[hasIndex].cb = cb
        else this.watchList.push({
            watchPage,
            cb
        })
    }
}

export default GoEasyBase